package com.samnative.pineapple.main;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.samnative.pineapple.adapter.MoviedetalCommnetAdapter;
import com.samnative.pineapple.adapter.MoviedetalJuzhaoAdapter;
import com.samnative.pineapple.adapter.MoviedetalYanyuanAdapter;
import com.samnative.pineapple.entity.HomeListModel;
import com.samnative.pineapple.entity.MovieDetalCommentModel;
import com.samnative.pineapple.http.HttpRequest;
import com.samnative.pineapple.http.JsonResult;
import com.samnative.pineapple.utils.GlideRequestOptions;
import com.samnative.pineapple.utils.GsonUtils;
import com.samnative.pineapple.value.Config;
import com.shashank.sony.fancytoastlib.FancyToast;
import com.willy.ratingbar.ScaleRatingBar;
import com.xiao.nicevideoplayer.NiceVideoPlayer;
import com.xiao.nicevideoplayer.NiceVideoPlayerManager;
import com.xiao.nicevideoplayer.TxVideoPlayerController;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 电影详情
 */
public class MovieDetailActivity extends BaseActivity implements View.OnClickListener {

    private String movieid = "";

    private HomeListModel model;

    private NestedScrollView nsv_content;
    private RelativeLayout rl_bar;

    private NiceVideoPlayer nice_video_player;
    private TxVideoPlayerController controller;

    private ImageView iv_img;
    private TextView tv_text1, tv_text2, tv_text3, tv_text4, tv_text5, tv_text6, tv_text7, tv_text8;
    private ScaleRatingBar rating;

    private RecyclerView rv_yan, rv_ju, rv_comment;
    private MoviedetalYanyuanAdapter yanyuanAdapter;
    private MoviedetalJuzhaoAdapter juzhaoAdapter;
    private MoviedetalCommnetAdapter commnetAdapter;

    private ImageView iv_btn1, iv_btn2, iv_btn3;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_movie_detail;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        ImmersionBar.with(this).statusBarDarkFont(false).init();
        movieid = getIntent().getStringExtra("movieid");
        find(R.id.tv_back).setOnClickListener(this);
        rl_bar = find(R.id.rl_bar);
        nsv_content = find(R.id.nsv_content);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            nsv_content.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                @Override
                public void onScrollChange(View view, int i, int i1, int i2, int i3) {

                    float num = i1 / 300f;
                    if (num >= 1) num = 1;
                    rl_bar.setAlpha(num);

                }
            });
        }

        controller = new TxVideoPlayerController(mContext);
        controller.onPlayModeChanged(NiceVideoPlayer.MODE_FULL_SCREEN);
        controller.setBacktoExit(true);
        controller.isCanFullScreen(true);
        nice_video_player = find(R.id.nice_video_player);
        nice_video_player.setController(controller);
        nice_video_player.setPlayerType(NiceVideoPlayer.TYPE_NATIVE);

        iv_img = find(R.id.iv_img);
        tv_text1 = find(R.id.tv_text1);
        tv_text2 = find(R.id.tv_text2);
        tv_text3 = find(R.id.tv_text3);
        tv_text4 = find(R.id.tv_text4);
        tv_text5 = find(R.id.tv_text5);
        tv_text6 = find(R.id.tv_text6);
        tv_text7 = find(R.id.tv_text7);
        tv_text8 = find(R.id.tv_text8);
        rating = find(R.id.rating);

        iv_btn1 = find(R.id.iv_btn1);
        iv_btn1.setOnClickListener(this);
        iv_btn2 = find(R.id.iv_btn2);
        iv_btn2.setOnClickListener(this);
        iv_btn3 = find(R.id.iv_btn3);
        iv_btn3.setOnClickListener(this);

        yanyuanAdapter = new MoviedetalYanyuanAdapter(R.layout.item_moviedetal_yanyuan);
        yanyuanAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                JSONArray jsonArray = new JSONArray();
                for (HomeListModel.PlotsWordsBean item : yanyuanAdapter.getData()) {
                    jsonArray.put(item.getImgUrl());

                }
                Intent intent = new Intent(mContext, PhotoPagerActivity.class);
                intent.putExtra("images", jsonArray.toString());
                intent.putExtra("position", position);
                startActivity(intent);
                overridePendingTransition(R.anim.activity_alpha_in, R.anim.activity_alpha_out);
            }
        });
        rv_yan = find(R.id.rv_yan);
        LinearLayoutManager manager1 = new LinearLayoutManager(mContext);
        manager1.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_yan.setLayoutManager(manager1);
        rv_yan.setAdapter(yanyuanAdapter);

        juzhaoAdapter = new MoviedetalJuzhaoAdapter(R.layout.item_moviedetal_juzhao);
        juzhaoAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                JSONArray jsonArray = new JSONArray();
                for (HomeListModel.PlotsImgBean item : juzhaoAdapter.getData()) {
                    jsonArray.put(item.getImgUrl());

                }
                Intent intent = new Intent(mContext, PhotoPagerActivity.class);
                intent.putExtra("images", jsonArray.toString());
                intent.putExtra("position", position);
                startActivity(intent);
                overridePendingTransition(R.anim.activity_alpha_in, R.anim.activity_alpha_out);
            }
        });
        rv_ju = find(R.id.rv_ju);
        LinearLayoutManager manager2 = new LinearLayoutManager(mContext);
        manager2.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_ju.setLayoutManager(manager2);
        rv_ju.setAdapter(juzhaoAdapter);

        commnetAdapter = new MoviedetalCommnetAdapter(R.layout.item_moviedetal_comment);
        rv_comment = find(R.id.rv_comment);
        rv_comment.setLayoutManager(new LinearLayoutManager(mContext));
        rv_comment.setAdapter(commnetAdapter);

        requestData();
    }


    @Override
    protected void onResume() {
        super.onResume();
        requestComment();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (nice_video_player != null && nice_video_player.isPlaying()) {
            nice_video_player.pause();
        }
    }

    @Override
    public void onBackPressed() {
        // 在全屏或者小窗口时按返回键要先退出全屏或小窗口，
        // 所以在Activity中onBackPress要交给NiceVideoPlayer先处理。
        if (NiceVideoPlayerManager.instance().onBackPressd()) return;
        super.onBackPressed();
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 在onStop时释放掉播放器
        NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();
    }


    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.tv_back:
                finish();
                break;
            case R.id.iv_btn1:
                requestDianzan();
                break;
            case R.id.iv_btn2:
                if (model.getIscollec().equals("1")) {
                    requestShoucang("2");
                } else {
                    requestShoucang("1");
                }
                break;
            case R.id.iv_btn3: {
                Intent intent = new Intent(mContext, PublishPinglunActivity.class);
                intent.putExtra("movieid", movieid);
                startActivity(intent);
            }
            break;
            default:
                break;
        }

    }

    /**
     * 获取详情
     */
    public void requestData() {
        Map<String, String> map = new HashMap<>();
        map.put("movieId", movieid);
        HttpRequest.request(this, "/client/movies/info", "", map, "GET", new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                try {
                    JSONObject jsondata = result.getJSONObject("item");
                    model = GsonUtils.fromJson(jsondata.toString(), HomeListModel.class);

                    controller.setTitle(model.getMovieName());
                    if (!TextUtils.isEmpty(model.getMovieUrl())) {
                        nice_video_player.setUp(model.getMovieUrl(), null);
                        nice_video_player.start();
                    }

                    Glide.with(mContext)
                            .load(Config._API_URL + model.getCover())//图片地址
                            .apply(GlideRequestOptions.OPTIONS_400_400)
                            .into(iv_img);
                    tv_text1.setText(model.getMovieName());
                    tv_text2.setText(model.getInfo());
                    tv_text3.setText(model.getOriginaName());
                    tv_text4.setText("影片时长:" + model.getTotalTime());
                    tv_text5.setText("上映时间:" + model.getReleaseDate());
                    tv_text6.setText(model.getScore() + "");
                    tv_text7.setText(model.getCounts() + "人点赞");
                    tv_text8.setText(model.getPlotDesc());
                    rating.setRating((float) (model.getScore() / 2));

                    if (model.getIscollec().equals("1")) {
                        iv_btn2.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.movieinfo_shoucang_p));
                    } else {
                        iv_btn2.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.movieinfo_shoucang));
                    }

                    yanyuanAdapter.getData().clear();
                    yanyuanAdapter.addData(model.getPlotsWords());

                    juzhaoAdapter.getData().clear();
                    juzhaoAdapter.addData(model.getPlotsImg());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void requestFinish() {
                super.requestFinish();

            }
        });
    }

    /**
     * 获取评论列表
     */
    public void requestComment() {
        Map<String, String> map = new HashMap<>();
        map.put("movieId", movieid);
        HttpRequest.request(this, "/client/comments/commentlist", "", map, "POST", new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                try {
                    JSONArray jsonArray = result.getJSONArray("list");
                    List<MovieDetalCommentModel> list = GsonUtils.fromJsonList(jsonArray.toString(), new TypeToken<List<MovieDetalCommentModel>>() {
                    }.getType());
                    commnetAdapter.getData().clear();
                    commnetAdapter.addData(list);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        });
    }

    /**
     * 获取评论列表
     */
    public void requestDianzan() {
        Map<String, String> map = new HashMap<>();
        map.put("movieId", movieid);
        HttpRequest.request(this, "/client/movies/likes", "", map, "POST", new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                FancyToast.showToast(mContext, "点赞成功", FancyToast.SUCCESS, false);
                requestData();
            }
        });
    }

    /**
     * 收藏/取消收藏
     */
    public void requestShoucang(String type) {
        Map<String, String> map = new HashMap<>();
        map.put("movieId", movieid);
        map.put("type", type);
        HttpRequest.request(this, "/client/collections/postcolle", "", map, "POST", new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                if (type.equals("1")) {
                    FancyToast.showToast(mContext, "收藏成功", FancyToast.SUCCESS, false);
                } else {
                    FancyToast.showToast(mContext, "取消收藏成功", FancyToast.SUCCESS, false);
                }
                requestData();
            }
        });
    }

}
